* Tariffs tau_it_S - industry level tariffs
* Updated March 3 moxnes@gmail.com

* Dependencies: This file requires running
* firm_patents2.do -> generates patentsfam2.dta
* weights_wic3.do -> Generates weightswic3.dta


cd /users/andreas/dropbox/work/patstat/data
global tmp "/tmp"

* Tariff for home country
use input_tariff, clear
ren inptariff* tauthq*
ren appln headq
ren out nacestr
save $tmp/inptariffreshapeHQ, replace

/* use $tmp/tmpnace, clear
ren tariff* tauthq*
ren appln headq
save $tmp/tmpnaceHQ, replace */

* ----------------------------------------------
* Restrict sample to firms with at least 1 patent in the post period
* ----------------------------------------------
use patentsfam3, clear
keep if y>=1992
keep if headq~=""
contract hrm
keep hrm
save $tmp/sample, replace

* ----------------------------------------------
* Merge tafiff data and weight wic
* ----------------------------------------------
use weightswic5_to1985, clear 				// Baseline
*use weightswic5_to1975, clear  			// Placebo
*use weightswic5_to1985_predicted, clear 	// Predicted weights

capture drop p tot
drop if headq==""

* Merge RTA variable
merge m:1 headq appln using rta, keep(match master)
drop _merge

* If missing RTA, set it to zero
gen Missrta = rta1992==.
foreach vv of varlist rta???? {
  replace `vv' = 0 if `vv'==.
}

* Input tariffs are NACE 2-digit
tostring nace2, gen(nacestr) force
replace nacestr = substr(nacestr,1,2)

* Merge input tariff for home country
merge m:1 headq nacestr using $tmp/inptariffreshapeHQ, keep(match master)

* If missing tariff, set it to zero for every year
gen MissInpTarhq = tauthq1992==.
foreach vv of varlist tauthq???? {
  replace `vv' = 0 if `vv'==.
}
save $tmp/tmp, replace

use $tmp/tmp, clear
gen homecty = appln_auth==headq 
gen homew = w if homecty==1

* Export weights
gen wEx = w
replace wEx = 0 if homecty==1
egen tmp = sum(wEx), by(hrm)
*replace wEx = wEx/tmp
gen wEx2 = wEx/tmp
drop tmp

*gen Missing = MissTar | MissTarhq | Missrta
*gen Missing = MissTar

* Assume bilateral tariff is zero if RTA
forvalues i=1992/2006 {
  gen tariffApplied`i' =  tauthq`i'*(~rta`i')
}

forvalues i=1992/2009 {
  gen tautInpImp`i' = tauthq`i'*wEx2 
} 

forvalues i=1992/2006 {
  gen tautInpAppImp`i' = tariffApplied`i'*wEx2
} 

gcollapse (sum) tautInpImp???? tautInpAppImp???? Miss*, by(hrm headq nace2) fast

save tauT5d_InpImp, replace

